package com.sp.system.user.interceptor.aop;

import com.google.gson.Gson;
import com.sp.system.user.core.utils.AddressUtil;
import com.sp.system.user.utils.context.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 *  切面拦截 spring 托管定义组件
 */
@Slf4j
@Aspect
@Order(5)
@Component
public class CmsRestAspect {

    private final String POINT_CUT = "execution(* com.tfkj.cms.tky..rest..*.*(..))";

//    @Autowired
//    private ICmsInterfaceLogService interfaceLogService;

    /**
     *  定义切点
     */
    @Pointcut(POINT_CUT)
    public void pointCut(){

        log.debug("CmsAspect->pointCut");
    }

    /**
     * 切点前 执行
     * @param joinPoint
     */
    @Before(value = "pointCut()")
    public void beforeExecution(JoinPoint joinPoint){
//        log.debug("beforeExecution");
    }


    /**
     *
     * @param proceedingJoinPoint
     * @return
     */
    @Around(value = "pointCut()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

//        log.debug("1" + loginAuthentication);

        return proceedingJoinPoint.proceed();
    }
    /**
     * 在切点方法之后执行
     * @param joinPoint
     */
    @AfterReturning(value = "pointCut()", returning="returnValue")
    public void afterExecution(JoinPoint joinPoint, Object returnValue){
        String userId = CurrentUser.getUserId();
        String userName = CurrentUser.getUserName();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String className = joinPoint.getTarget().getClass().getName();   //获取当前类名
        Method method = signature.getMethod();
        String methodName = method.getName();   //获取当前方法名

        //获取requestBody 参数信息,过滤掉 ServletRequest 和 ServletResponse 类型的参数
        Object object = Arrays.stream(joinPoint.getArgs()).filter(t ->!( t instanceof ServletRequest) && !( t instanceof ServletResponse) ).collect(Collectors.toList());
        //请求参数转成jsonString
        String requestBody =  new Gson().toJson(object);

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = "获取request失败.";
        String ip = "00：00";
        if (null != request) {
            url = request.getRequestURI();
            ip = AddressUtil.getIpAddress(request);
        }
        /*CmsInterfaceLog interfaceLog = new CmsInterfaceLog();
        interfaceLog.setOperateId(userId);
        interfaceLog.setOperateName(userName);
        interfaceLog.setOperateClazz(className);
        interfaceLog.setOperateMethod(methodName);
        interfaceLog.setOperateUrl(url);

        String responseBody = new Gson().toJson(returnValue);

        if(requestBody.length() >1000){
            requestBody = requestBody.substring(0,1000);
        }
        if(responseBody.length() >1000){
            responseBody = responseBody.substring(0,1000);
        }
        interfaceLog.setResponseBody(responseBody);
        interfaceLog.setRequestBody(requestBody);
        interfaceLog.setIp(ip);

        try {
            interfaceLogService.save(interfaceLog);
        } catch (Exception e) {
            log.error("日志保存失败{}",e);

        }*/
    }


}
